<?php

namespace app\common\service;
use app\common\service\OrderUser as OrderUserService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderDelivery as OrderDeliveryService;
use app\common\service\Sku as SkuService;
use app\common\service\JinPengCut as JinPengCutService;
use app\common\service\Base;
use jinpeng\Jinpeng;
use think\facade\Env;

class Order extends Base
{

	/**
	 * 根据ID获取记录信息
	 *
	 * @author KING
	 * @date 2020年7月9日
	 *
	 * @param integer $id
	 * @param string $field
	 * @return array
	 */
	public function getInfoById($id, $field='*') {
		if (empty($id)) return [];
		return db('order')->where('id', $id)->field($field)->findOrEmpty();
	}

	/**
	 * 根据客户订单号获取订单详情
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @param String $clientOrdernum
	 * @param string $field
	 * @return array
	 */
	public function getInfoByClientOrdernum($clientOrdernum, $field='*') {
		if (empty($clientOrdernum)) return [];
		return db('order')->where('client_ordernum',$clientOrdernum)->where('status', '<>', 99)->field($field)->findOrEmpty();
	}

	/**
	 * 根据订单号获取SKU
	 *
	 * @author KING
	 * @date 2020年7月7日
	 *
	 * @param string $clientOrdernum
	 * @return string
	 */
	public function getSkuByClientOrdernum($clientOrdernum) {
		if (empty($clientOrdernum)) return '';
		return db('order')->where('client_ordernum', $clientOrdernum)->value('sku', '');
	}

	/**
	 * 获取近N日产能
	 *
	 * @author KING
	 * @date 2020年7月27日
	 *
	 * @param integer $days
	 * @param integer $factoryId
	 * @param integer $isAutoImport
	 */
	public function getOutputByDays($days, $factoryId=0, $isAutoImport=0) {
		$dayStart = strtotime("-{$days} day 00:00:00");
		$dayEnd = strtotime('0 day 00:00:00')-1;
		$where = [
			['o.status', 'in', [0, 1, 2]],
			['o.tail_status', '=', 1],
			['o.tail_over_time', 'between', [$dayStart, $dayEnd]],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) {
			$where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		}
		$info = db('order_size os')->join('order o', 'o.id = os.order_id')->join('sku s', 's.sku = o.sku')->where($where)->field('sum(os.daohuo_count * s.cost) as num')->findOrEmpty();
		$result = [
			'money' => round(arrayGet($info, 'num', 0), 1),
			'jianshu' => db('order_size os')->join('order o', 'o.id = os.order_id')->where($where)->sum('os.daohuo_count'),
		];
		$result['avgMoney'] = round($result['money']/$days, 1);
		$result['avgJianshu'] = round($result['jianshu']/$days);
		return $result;
	}

	/**
	 * 获取在途产能
	 *
	 * @author KING
	 * @date 2020年7月27日
	 *
	 * @param integer $factoryId
	 * @param integer $isAutoImport
	 * @param integer $isOrderList	是否获取订单列表
	 */
	public function getOutputIng($factoryId=0, $isAutoImport=0, $isOrderList=false) {
		$where = [
			['o.status', 'in', [0, 1]],
			['o.tail_status', '=', 0],
		];
		if ($factoryId) {
			$where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		}
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}

		if ($isOrderList) {
			$fieldStatus = "(case when o.status=99 then '已废弃' when o.status=2 then '已完成' when o.tail_status=1 then '已打包' when o.chejian_status=1 then '已车缝' when o.caichuang_status=1 then '已裁剪' when o.caigou_status=1 then '已采购' else '采购中' end) as status_txt";
			$field = 'o.id,o.client_ordernum,o.factory_id,o.quantity,o.create_time,'.$fieldStatus;
			return db('order o')->where($where)->field($field)->order('create_time desc')->select();
		} else {
			$info = db('order_size os')->join('order o', 'o.id = os.order_id')->join('sku s', 's.sku = o.sku')->where($where)->field('sum(os.order_count * s.cost) as num')->findOrEmpty();
			$result = [
				'money' => round(arrayGet($info, 'num', 0), 1),
				'jianshu' => db('order_size os')->join('order o', 'o.id = os.order_id')->where($where)->sum('os.order_count'),
				'orders' => db('order o')->where($where)->count(1),
			];
		}
		return $result;
	}

	/**
	 * 根据条件获取订单数
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @return integer
	 */
	public function getOrdersByCondition($factoryId=0, $andWhere='', $isAutoImport=0) {
		$where = [];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		return db('order o')->join('sku s', 's.sku = o.sku')->where($where)->where($andWhere)->count(1);
	}

	/**
	 * 根据条件获取下单件数
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @return integer
	 */
	public function getQuantityByCondition($factoryId=0, $andWhere='', $isAutoImport=0) {
		$where = [];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		return db('order o')->join('sku s', 's.sku = o.sku')->where($where)->where($andWhere)->sum('quantity');
	}

	/**
	 * 根据条件获取在途件订单数
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @param boolean $isOrderList	是否获取订单列表
	 * @return integer
	 */
	public function getIngOrderByRange($factoryId=0, $andWhere='', $isAutoImport=0, $isOrderList=false) {
		$where = [
			['o.status', 'in', [0, 1]],
			['o.tail_status', '=', 0],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isOrderList) {
			$field = 'o.id,o.client_ordernum,o.factory_id,o.quantity,o.create_time';
			return db('order o')->where($where)->field($field)->order('create_time desc')->select();
		} else {
			return db('order o')->join('sku s', 's.sku = o.sku')->where($where)->where($andWhere)->count(1);
		}
	}

	/**
	 * 根据条件获取在途件数
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @return integer
	 */
	public function getIngCountByRange($factoryId=0, $andWhere='', $isAutoImport=0) {
		$where = [
			['o.status', 'in', [0, 1]],
			['o.tail_status', '=', 0],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		return db('order o')->join('sku s', 's.sku = o.sku')->where($where)->where($andWhere)->sum('o.quantity');
	}

	/**
	 * 根据条件获取在途金额
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @return number
	 */
	public function getIngMoneyByRange($factoryId=0, $andWhere='', $isAutoImport=0) {
		$where = [
			['o.status', 'in', [0, 1]],
			['o.tail_status', '=', 0],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		$info = db('order o')->join('sku s', 's.sku = o.sku')->where($where)->where($andWhere)->field("sum(o.quantity * s.cost) as num")->findOrEmpty();
		return round(arrayGet($info, 'num', 0), 2);
	}

	/**
	 * 根据条件获取下单件数(所有订单)
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $startTime
	 * @param integer $endTime
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @return integer
	 */
	public function getOrderCountAllByRange($startTime, $endTime, $factoryId=0, $andWhere='', $isAutoImport=0) {
		$where = [
			['o.status', '=', 2],
			['o.create_time', 'between', [$startTime, $endTime]],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		return db('order o')->join('sku s', 's.sku = o.sku')->where($where)->where($andWhere)->sum('o.quantity');
	}

	/**
	 * 根据条件获取下单金额(所有订单)
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $startTime
	 * @param integer $endTime
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @return number
	 */
	public function getOrderMoneyAllByRange($startTime, $endTime, $factoryId=0, $andWhere='', $isAutoImport=0) {
		$where = [
			['o.status', 'in', [0, 1, 2]],
			['o.create_time', 'between', [$startTime, $endTime]],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		$info = db('order o')->join('sku s', 's.sku = o.sku')->where($where)->where($andWhere)->field("sum(o.quantity * s.cost) as num")->findOrEmpty();
		return round(arrayGet($info, 'num', 0), 2);
	}

	/**
	 * 统计数据
	 *
	 * @return array
	 */
	public function getOrderStat($factoryId=0, $isAutoImport=0) {
		$cacheSuffix = ADMIN_ID . '-' . str_replace(',', '_', $factoryId) . '-' . $isAutoImport;

		// 【采购】已下单未采购完成
		// 总件数|订单数|超期总件数|超期总单数
		$cgCount = $cgOrder = $cgCountOverdue = $cgOrderOverdue = 0;
		$cgOverdue = 86400 * 2; // 2天
		$where = [
			['status', 'in', [0, 1]],
			['caigou_status', '=', 0],
		];
		if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['is_auto_import', '=', $isAutoImport];
		$cgList = db('order')->where($where)->field('id,create_time,quantity')->select();
		$cgOrder = count($cgList); // 订单数
		$cgCount = $cgCountOverdue = 0;
		$cgOrderids = $cgOrderidsOverdue = [];
		foreach ($cgList as $k => $v) {
			if (time() - $v['create_time'] > $cgOverdue) { // 超期
				$cgOrderOverdue++; // 超期订单数
				$cgOrderidsOverdue[] = $v['id'];
				$cgCountOverdue += $v['quantity'];
			}
			$cgOrderids[] = $v['id'];
			$cgCount += $v['quantity'];
		}
		cache(STAT_CG.$cacheSuffix, $cgOrderids, 86400);
		cache(STAT_CGOVERDUE.$cacheSuffix, $cgOrderidsOverdue, 86400);

		// 【面料处理】最大客户用料的面料已到料且未开始裁剪
		$where = [
			['status', 'in', [0, 1]],
			['caichuang_status', '=', 0],
			['caichuang_can_do', '=', 0],
		];
		if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['is_auto_import', '=', $isAutoImport];
		$mlList = db('order')->where($where)->where('id', 'IN', function ($query) {
			$query->table(Env::get('database.prefix', 'wx_').'order_material')->where('caichuang_standard = 1 and arrive_time > 0')->field('order_id');
		})->field('id,quantity')->select();
		$mlCount = array_sum(array_column($mlList, 'quantity'));
		$mlOrder = count($mlList);
		cache(STAT_ML.$cacheSuffix, array_column($mlList, 'id'), 86400);

		// 【裁剪】已采购未裁剪完成
		$cjCount = $cjOrder = $cjCountOverdue = $cjOrderOverdue = 0;
		$cjOverdue = 86400 * 1; // 1天
		$where = [
			['status', 'in', [0, 1]],
			['caigou_status', '=', 1],
			['caichuang_status', '=', 0],
		];
		if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['is_auto_import', '=', $isAutoImport];
		$cjList = db('order')->where($where)->field('id,caigou_over_time,quantity')->select();
		$cjOrder = count($cjList); // 订单数
		$cjCount = $cjCountOverdue = 0;
		$cjOrderids = $cjOrderidsOverdue = [];
		foreach ($cjList as $k => $v) {
			if (time() - $v['caigou_over_time'] > $cjOverdue) { // 超期
				$cjOrderOverdue++; // 超期订单数
				$cjOrderidsOverdue[] = $v['id'];
				$cjCountOverdue += $v['quantity'];
			}
			$cjOrderids[] = $v['id'];
			$cjCount += $v['quantity'];
		}
		cache(STAT_CJ.$cacheSuffix, $cjOrderids, 86400);
		cache(STAT_CJOVERDUE.$cacheSuffix, $cjOrderidsOverdue, 86400);

		$orderSizeService = new OrderSizeService();

		// 【车间】已下车位未完成
		$chejCount = $chejOrder = $chejCountOverdue = $chejOrderOverdue = 0;
		$chejOverdue = 86400 * 3; // 3天
		$where = [
			['status', 'in', [0, 1]],
			['caichuang_status', '=', 1],
			['chejian_status', '=', 0],
		];
		if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['is_auto_import', '=', $isAutoImport];
		$chejList = db('order')->where($where)->field('id,caichuang_over_time')->select();
		$chejOrder = count($chejList); // 订单数
		$chejOrderids = $chejOrderidsOverdue = [];
		foreach ($chejList as $k => $v) {
			if (time() - $v['caichuang_over_time'] > $chejOverdue) { // 超期
				$chejOrderOverdue++; // 超期订单数
				$chejOrderidsOverdue[] = $v['id'];
			}
			$chejOrderids[] = $v['id'];
		}
		$chejCountOverdue = $orderSizeService->getShicaiCount($chejOrderidsOverdue);
		$chejCount = $orderSizeService->getShicaiCount($chejOrderids);
		cache(STAT_CHEJ.$cacheSuffix, $chejOrderids, 86400);
		cache(STAT_CHEJOVERDUE.$cacheSuffix, $chejOrderidsOverdue, 86400);

		// 【尾部】车间已完成尾部未完成
		$wbCount = $wbOrder = $wbCountOverdue = $wbOrderOverdue = 0;
		$wbOverdue = 86400 * 1; // 1天
		$where = [
			['status', 'in', [0, 1]],
			['chejian_status', '=', 1],
			['tail_status', '=', 0],
		];
		if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['is_auto_import', '=', $isAutoImport];
		$wbList = db('order')->where($where)->field('id,chejian_over_time,quantity')->select();
		$wbOrder = count($wbList); // 订单数
		$wbCount = $wbCountOverdue = 0;
		$wbOrderids = $wbOrderidsOverdue = [];
		foreach ($wbList as $k => $v) {
			if (time() - $v['chejian_over_time'] > $wbOverdue) { // 超期
				$wbOrderOverdue++; // 超期订单数
				$wbOrderidsOverdue[] = $v['id'];
			}
			$wbOrderids[] = $v['id'];
		}
		$wbCountOverdue = $orderSizeService->getShicaiCount($wbOrderidsOverdue);
		$wbCount = $orderSizeService->getShicaiCount($wbOrderids);
		cache(STAT_WB.$cacheSuffix, $wbOrderids, 86400);
		cache(STAT_WBOVERDUE.$cacheSuffix, $wbOrderidsOverdue, 86400);

		// 【已后整待发货】mes 1待打包 + 2已打包 + 3待发货
		$dchCount = $dchOrder = $dchCountOverdue = $dchOrderOverdue = 0;
		$dchOverdue = 86400 * 1; // 1天
		$where = [
			['status', 'in', [0, 1]],
			['tail_status', '=', 1],
		];
		if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['is_auto_import', '=', $isAutoImport];
		$dchList = db('order')->where($where)->field('id,tail_over_time')->select();
		$dchOrder = count($dchList); // 订单数
		$dchCount = $dchCountOverdue = 0;
		$dchOrderids = $dchOrderidsOverdue = [];
		foreach ($dchList as $k => $v) {
			if (time() - $v['tail_over_time'] > $dchOverdue) { // 超期
				$dchOrderOverdue++; // 超期订单数
				$dchOrderidsOverdue[] = $v['id'];
			}
			$dchOrderids[] = $v['id'];
		}
		$orderDeliveryService = new OrderDeliveryService();
		$dchCountOverdue = $orderDeliveryService->getDeliveryCount($dchOrderidsOverdue, [1,2,3]);
		$dchCount = $orderDeliveryService->getDeliveryCount($dchOrderids, [1,2,3]);
		cache(STAT_DCH.$cacheSuffix, $dchOrderids, 86400);
		cache(STAT_DCHOVERDUE.$cacheSuffix, $dchOrderidsOverdue, 86400);

		// 【合计】
		$hjCount = $hjOrder = $hjCountOverdue = $hjOrderOverdue = 0;
		$hjOverdue = 86400 * 10; // 10天
		$where = [
			['status', 'in', [0, 1]],
		];
		if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['is_auto_import', '=', $isAutoImport];
		$hjList = db('order')->where($where)->field('id,create_time,quantity')->select();
		$hjOrder = count($hjList); // 订单数
		$hjCount = $hjCountOverdue = 0;
		$hjOrderids = $hjOrderidsOverdue = [];
		foreach ($hjList as $k => $v) {
			if (time() - $v['create_time'] > $hjOverdue) { // 超期
				$hjOrderOverdue++; // 超期订单数
				$hjOrderidsOverdue[] = $v['id'];
				$hjCountOverdue += $v['quantity'];
			}
			$hjOrderids[] = $v['id'];
			$hjCount += $v['quantity'];
		}
		cache(STAT_HJ.$cacheSuffix, $hjOrderids, 86400);
		cache(STAT_HJOVERDUE.$cacheSuffix, $hjOrderidsOverdue, 86400);

		// 合计总加工费
		$where = [
			['o.status', 'in', [0, 1]],
		];
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['o.is_auto_import', '=', $isAutoImport];
		$info = db('order o')->join('sku s', 'o.sku = s.sku')->where($where)->field('sum(o.quantity*s.cost) as num')->findOrEmpty();
		$hjTotalCost = arrayGet($info, 'num', 0);

		// 【裁片外发】
		$cpwfCgOrder = $cpwfCgCount = $cpwfCjOrder = $cpwfCjCount = $cpwfHjOrder = $cpwfHjCount = 0;
		$where = [
			['status', 'in', [0, 1]],
			['caigou_status', '=', 0],
			['outgo_status', '=', 2],
		];
		if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['is_auto_import', '=', $isAutoImport];
		$cpwfCgList = db('order')->where($where)->field('id,quantity')->select();
		$cpwfCgOrder = count($cpwfCgList); // 采购总单数
		cache(STAT_CPWFCG.$cacheSuffix, array_column($cpwfCgList, 'id'), 86400);
		$cpwfCgCount = array_sum(array_column($cpwfCgList, 'quantity'));	// 采购总件数

		$where = [
			['status', 'in', [0, 1]],
			['caigou_status', '=', 1],
			['caichuang_status', '=', 0],
			['outgo_status', '=', 2],
		];
		if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['is_auto_import', '=', $isAutoImport];
		$cpwfCjList = db('order')->where($where)->field('id,quantity')->select();
		$cpwfCjOrder = count($cpwfCjList); // 裁床总单数
		cache(STAT_CPWFCJ.$cacheSuffix, array_column($cpwfCjList, 'id'), 86400);
		$cpwfCgCount = array_sum(array_column($cpwfCjList, 'quantity'));	// 裁床总件数

		$where = [
			['status', 'in', [0, 1]],
			['outgo_status', '=', 2],
		];
		if ($factoryId) $where[] = ['factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['is_auto_import', '=', $isAutoImport];
		$cpwfHJList = db('order')->where($where)->field('id,quantity')->select();
		$cpwfHjOrder = count($cpwfHJList); // 总订单数
		cache(STAT_CPWFHJ.$cacheSuffix, array_column($cpwfHJList, 'id'), 86400);
		$cpwfHjCount = array_sum(array_column($cpwfHJList, 'quantity'));	// 总件数

		// 整理结果
		$result = array();
		$result['cg'][1] = $cgCount;
		$result['cg'][2] = $cgOrder;
		$result['cg'][3] = $cgCountOverdue;
		$result['cg'][4] = $cgOrderOverdue;

		$result['ml'][1] = $mlCount;
		$result['ml'][2] = $mlOrder;

		$result['cj'][1] = $cjCount;
		$result['cj'][2] = $cjOrder;
		$result['cj'][3] = $cjCountOverdue;
		$result['cj'][4] = $cjOrderOverdue;
		$result['chej'][1] = $chejCount;
		$result['chej'][2] = $chejOrder;
		$result['chej'][3] = $chejCountOverdue;
		$result['chej'][4] = $chejOrderOverdue;

		$result['wb'][1] = $wbCount;
		$result['wb'][2] = $wbOrder;
		$result['wb'][3] = $wbCountOverdue;
		$result['wb'][4] = $wbOrderOverdue;
		$result['dch'][1] = $dchCount;
		$result['dch'][2] = $dchOrder;
		$result['dch'][3] = $dchCountOverdue;
		$result['dch'][4] = $dchOrderOverdue;
		// 合计
		$result['hj'][1] = $hjCount;
		$result['hj'][2] = $hjOrder;
		$result['hj'][3] = $hjCountOverdue;
		$result['hj'][4] = $hjOrderOverdue;
		$result['hj'][5] = $hjTotalCost;
		// 裁片外发
		$result['cpwf'][1] = $cpwfCgCount;
		$result['cpwf'][2] = $cpwfCgOrder;
		$result['cpwf'][3] = $cpwfCjCount;
		$result['cpwf'][4] = $cpwfCjOrder;
		$result['cpwf'][5] = $cpwfHjCount;
		$result['cpwf'][6] = $cpwfHjOrder;
		return $result;
	}

	/**
	 * 更新订单
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @param array $data
	 * @param array $where
	 * @return integer
	 */
	public function updateInfo($data, $where=[]) {
		$data['update_time'] = time();
		return db('order')->where($where)->update($data);
	}
	/**
	 * 检查订单是否异常
	 *
	 * @author 飞燕
	 * @date 2021年3月30日

	 * @param array $orderId
	 * @return bool
	 */
	public function checkExceptionStatus($orderId) {
		$info = $this->getInfoById($orderId);
		if ($info['exception_num']>0) return true;
		return false;
	}

	/**
	 * 更新订单异常状态
	 *
	 * @author 飞燕
	 * @date 2021年3月31日

	 * @param array $orderId
	 * @return bool
	 */
	public function updateExceptionNum($orderId) {
		$oeCount=db('order_exception')->where("order_id=".$orderId." and status=0")->count('id');
		db('order')->where('id',$orderId)->update(['exception_num'=>$oeCount,'update_time'=>time()]);
	}

	/**
	 * 同步金鹏订单
	 *
	 * @author 飞燕
	 * @date 2021年3月31日

	 * @param array $orderId
	 * @return bool
	 */
	public function syncJinpengOrder($orderId,$action) {
		$orderSizeService = new OrderSizeService();
		$skuService = new SkuService();
		$osList=$orderSizeService->getListByOrderId($orderId);
		$oInfo=$this->getInfoById($orderId);
		$sInfo=$skuService->getInfoBySku($oInfo['sku'], 'id');
		$jp=new Jinpeng();
        $factoryKV = getFactoryKV(false);
		foreach ($osList as $kos => $vos) {
			$detail[]=[
				'action'=>$action,
				'color_id'=>'',
				'color'=>'',
				'size_id'=>$vos['size_name'],
				'size'=>$vos['size_name'],
				'qty'=>$vos['order_count'],
			];
		}
        if($oInfo['factory_id']<=0){
            return ['msg'=>'检测到订单'.$oInfo['client_ordernum'].'没有分配工厂，请先分配工厂','succeedNum'=>0,'failNum'=>0];
        }
        $orderInfo=['client_ordernum'=>$oInfo['client_ordernum'],'factory_id'=>$oInfo['factory_id'],'factory_name'=>isset($factoryKV[$oInfo['factory_id']])?$factoryKV[$oInfo['factory_id']] : '' ];
		$res1=$jp->syncOrder($action,$oInfo['id'],$orderInfo,$sInfo['id'],$oInfo['sku'],$detail);
		$jinpengStatus=2;
		if($res1['succeed']==true) $jinpengStatus=1;
		if($res1['succeed']==true && $action=="dele") {
			$jinpengStatus=3;
			$a=db('order_user')->where('order_id',$orderId)->update(['jinpeng_status'=>3,'update_time'=>time()]);			//dump($a);
		}
		if ($oInfo['jinpeng_status'] == 1 && $jinpengStatus == 2) {
			// 已成功的，再次出现失败不记录
		} else {
			db('order')->where('id',$oInfo['id'])->update(['jinpeng_status'=>$jinpengStatus,'jinpeng_time'=>time(),'update_time'=>time()]);
		}
		//推送订单工序及工价至金鹏
        $putRet=$this->syncPutSkuProcessListToJP($oInfo['sku'],$oInfo['id'],$oInfo['client_ordernum']);
        $res1['putProcessRet']=$putRet;
		return $res1;
	}

    /**
     * 推送某个订单的sku的工价信息至金鹏
     */
    public function syncPutSkuProcessListToJP($sku,$orderId,$clientOrdernum,$source='follow_cut'){
        $where = [];
        $where[] = ['sku', '=', $sku];
        $where[] = ['process_stage', 'in', [2,3]];
        $havedata=db("sku_process_price")->where($where)->find();
        if(empty($havedata)){
            $this->insertProcessMemoData($sku);
        }
        //2,获取订单 产品信息  工价信息
        $list = db('sku_process_price spr')
            ->field('spr.id,spr.sku,spr.process_stage,spr.process_name,spr.process_price,spr.create_time')
            ->where($where)->order('spr.process_stage asc,spr.id asc')->select();
        $process_list = [];
        if(count($list)<1){
            return ['data' =>'同步失败' ,'succeed' =>false,'msg' =>'同步失败，未找到款式工价信息'];
        }
        foreach ($list as $k => $v) {
            $process_list[] = [
                'id' => $v['id'],
                'process_name' => base64_encode($v['process_name']),
                'process_price' => $v['process_price'],
                'process_stage' => $v['process_stage'],
                'create_time' => $v['create_time'],
            ];
        }
        //3,推送工序工价及工序id
        $result = (new \jinpeng\Jinpeng())->syncSkuPrice($source, $orderId, $clientOrdernum, $sku, $process_list);
        //金鹏返回格式    [[data] => 单据保存成功 [succeed] => 1 [msg] => [msg_code] => [gex] =>]
        if(isset($result['succeed']) && $result['succeed']==1){
            $result['msg']='工序同步金鹏成功';
            $a=db('sku_process_price')->where('sku',$sku)->update(['upload_to_golds'=>1,'upload_jp_time'=>time()]);
        }
        return $result;
    }

    //创建默认工序
    public function insertProcessMemoData($addSku){
        $createtime=time();$insetRet='';
        $havedata=db("sku_process_price")->where(['sku'=>$addSku])->order("process_stage desc")->find();
        if(empty($havedata) || $havedata['process_stage']==1) {  //不存在车尾工序数据
            $cutProcessSql=$havedata['process_stage']==1 ?'': "('$addSku','5','裁剪','1','0.00','0','0','','1','29','$createtime','$createtime'),"; //不重复增加裁床工序
            $insertSql = "insert into `wx_sku_process_price` (`sku`, `process_name_id`, `process_name`, `process_stage`, `process_price`, `upload_jp_time`, `upload_to_golds`, `remark`, `status`, `admin_id`, `create_time`, `update_time`) values
            $cutProcessSql('$addSku','10','平车','2','0.00','0','0','','1','29','$createtime','$createtime')
            ,('$addSku','11','打边','2','0.00','0','0','','1','29','$createtime','$createtime'),('$addSku','12','冚车','2','0.00','0','0','','1','29','$createtime','$createtime')
            ,('$addSku','21','查货','3','0.00','0','0','','1','29','$createtime','$createtime'),('$addSku','20','大烫','3','0.00','0','0','','1','29','$createtime','$createtime')
            ,('$addSku','23','包装','3','0.00','0','0','','1','29','$createtime','$createtime'),('$addSku','22','剪线','3','0.00','0','0','','1','29','$createtime','$createtime');";
            $insetRet = db()->query($insertSql);
        }
        return $insetRet;
    }


	/**
	 * 同步金鹏裁剪
	 *
	 * @author 飞燕
	 * @date 2021年3月31日

	 * @param array $orderId
	 * @return bool
	 */
	public function syncJinpengCut($orderId,$action1,$action2,$jinPengData=[]){
		$orderUserService = new OrderUserService();
		$jinPengCutService = new JinPengCutService();
		$ouList=$orderUserService->getListByOrderId($orderId);
		if(!empty($jinPengData)){
			$ouList=$jinPengData;
			$midStr= implode(',', array_column($ouList, 'mid'));
			$where[]=['mid','in',$midStr];
		}
        $factoryKV = getFactoryKV(false);
		$oInfo=$this->getInfoById($orderId);
		$jp=new Jinpeng();
		foreach ($ouList as $key => $value) {
			$ouData[$value['chuanghao']][]=$value;
		}
		$failNum=$succeedNum=0;
		$status=1;
		$msgArr=[];
		foreach ($ouData as $k => $v) {
			foreach ($v as $kk => $vv) {

				$detail1[]=[
					'action'=>$action2,//$vv['jinpeng_status']==4?'del':'edit',
					'bar_num'=>$vv['zhahao'],
					'color_id'=>'',
					'size_id'=>$vv['size_name'],
					'qty'=>$vv['jianshu'],
				];

				$osJinPengData=[
					'jinpeng_time'=>time(),
					'jinpeng_qty'=>$vv['jianshu'],
					'jinpeng_size_name'=>$vv['size_name'],
					'jinpeng_chuanghao'=>$k,
					'update_time'=>time()
				];
				db('order_user')->where('mid',$vv['mid'])->update($osJinPengData);
			}//dump($action1);dump($detail1);exit();
            if($oInfo['factory_id']<=0){
                return ['msg'=>'检测到订单'.$oInfo['client_ordernum'].'没有分配工厂，请先分配工厂','succeedNum'=>0,'failNum'=>0];
            }
            $orderInfo=['client_ordernum'=>$oInfo['client_ordernum'],'factory_id'=>$oInfo['factory_id'],'factory_name'=>isset($factoryKV[$oInfo['factory_id']])?$factoryKV[$oInfo['factory_id']] : '' ];
			$res2=$jp->syncCut($action1,$oInfo['id'],$orderInfo,$k,date('Y-m-d',$v[0]['create_time']),$detail1); //dump($res2);dump($detail1);
			$status=2;//同步失败状态
			if($res2['succeed']==true){
				$whereoc=[
					'order_id'=>$orderId,
					'chuanghao'=>$k,
					'jinpeng_status'=>1
				];
				$ouocList=db('order_user')->where($whereoc)->order('zhahao asc')->select();
				$zhaohaoTxt= implode(',', array_column($ouocList, 'zhahao'));
				$jpData=[
					'order_id'=>$oInfo['id'],
					'client_ordernum'=>$oInfo['client_ordernum'],
					'chuanghao'=>$k,
					'zhahao_txt'=>$zhaohaoTxt,
					'status'=>$zhaohaoTxt==""?0:1,
					'create_time'=>time(),
					'update_time'=>time()
				];
				db('jinpeng_cut')->insert($jpData,true);
				$succeedNum++;
			}else{
				$msgArr[]=$res2['msg'];
				$failNum++;
			}
			$where[]=[
				['order_id','=',$oInfo['id']],
				['chuanghao','=',$k]
			];
			$status=1;//同步成功
			if($action2!="dele" || $action1=='dele') {
				if($action1=='dele') $status=3;//同步删除
				db('order_user')->where($where)->update(['jinpeng_status'=>$status,'update_time'=>time()]);
			}

		}
		return ['msg'=>$msgArr,'succeedNum'=>$succeedNum,'failNum'=>$failNum];
	}
}